<!DOCTYPE html>
<html lang="zh-CN" layout:decorate="~{layout}">
<head>
    <title>测试报告 - HTTP性能测试工具</title>
</head>
<body>
    <div layout:fragment="content" class="container-fluid">
        <!-- 页面头部 -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h2><i class="fas fa-chart-bar"></i> 测试报告</h2>
                <p class="text-muted mb-0">查看和分析性能测试结果</p>
            </div>
            <div class="btn-group" role="group">
                <button type="button" class="btn btn-outline-primary" onclick="refreshReports()">
                    <i class="fas fa-sync"></i> 刷新
                </button>
                <button type="button" class="btn btn-outline-secondary" onclick="exportReports()">
                    <i class="fas fa-download"></i> 导出
                </button>
            </div>
        </div>

        <!-- 搜索和筛选 -->
        <div class="card mb-4">
            <div class="card-body">
                <div class="row">
                    <div class="col-md-4">
                        <div class="input-group">
                            <span class="input-group-text"><i class="fas fa-search"></i></span>
                            <input type="text" class="form-control" id="search-input" placeholder="搜索测试名称...">
                        </div>
                    </div>
                    <div class="col-md-3">
                        <select class="form-select" id="format-filter">
                            <option value="">全部格式</option>
                            <option value="html">HTML报告</option>
                            <option value="json">JSON格式</option>
                            <option value="csv">CSV格式</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <select class="form-select" id="time-filter">
                            <option value="">全部时间</option>
                            <option value="today">今天</option>
                            <option value="week">最近一周</option>
                            <option value="month">最近一月</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <button type="button" class="btn btn-outline-secondary w-100" onclick="applyFilters()">
                            <i class="fas fa-filter"></i> 筛选
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 报告列表 -->
        <div class="row" id="reports-container">
            <!-- 动态加载的报告卡片将在这里显示 -->
        </div>

        <!-- 空状态提示 -->
        <div id="no-reports" class="text-center text-muted py-5 d-none">
            <i class="fas fa-chart-line fa-3x mb-3"></i>
            <h4>暂无测试报告</h4>
            <p>完成测试后，报告将在这里显示</p>
            <a href="/tests" class="btn btn-primary">
                <i class="fas fa-play"></i> 去执行测试
            </a>
        </div>

        <!-- 加载中状态 -->
        <div id="loading" class="text-center py-5">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">加载中...</span>
            </div>
            <p class="mt-3 text-muted">正在加载报告...</p>
        </div>

        <!-- 报告详情模态框 -->
        <div class="modal fade" id="reportDetailModal" tabindex="-1">
            <div class="modal-dialog modal-xl">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">报告详情</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div id="report-detail-content">
                            <!-- 报告详情将在这里显示 -->
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                        <button type="button" class="btn btn-outline-primary" id="download-report-btn" onclick="downloadReport()">
                            <i class="fas fa-download"></i> 下载报告
                        </button>
                        <button type="button" class="btn btn-primary" id="view-full-report-btn" onclick="viewFullReport()">
                            <i class="fas fa-external-link-alt"></i> 完整报告
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 报告比较模态框 -->
        <div class="modal fade" id="compareModal" tabindex="-1">
            <div class="modal-dialog modal-xl">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">报告对比</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="compare-report-1" class="form-label">基准报告</label>
                                <select class="form-select" id="compare-report-1">
                                    <option value="">选择报告...</option>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label for="compare-report-2" class="form-label">对比报告</label>
                                <select class="form-select" id="compare-report-2">
                                    <option value="">选择报告...</option>
                                </select>
                            </div>
                        </div>
                        <div id="compare-result">
                            <!-- 比较结果将在这里显示 -->
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                        <button type="button" class="btn btn-primary" onclick="performComparison()">
                            <i class="fas fa-balance-scale"></i> 开始对比
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- JavaScript -->
    <th:block layout:fragment="scripts">
        <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
        <script>
            let currentReportDetail = null;
            let allReports = [];

            $(document).ready(function() {
                loadReportList();
                
                // 搜索框回车事件
                $('#search-input').on('keypress', function(e) {
                    if (e.which === 13) {
                        applyFilters();
                    }
                });
            });

            function loadReportList() {
                $('#loading').show();
                $('#reports-container').empty();
                $('#no-reports').hide();
                
                $.get('/api/reports')
                    .done(function(reports) {
                        $('#loading').hide();
                        allReports = reports;
                        
                        if (reports.length === 0) {
                            $('#no-reports').show();
                            return;
                        }
                        
                        reports.forEach(report => {
                            createReportCard(report);
                        });
                    })
                    .fail(function() {
                        $('#loading').hide();
                        AppUtils.showError('加载报告列表失败');
                    });
            }

            function createReportCard(report) {
                const successRate = report.totalRequests > 0 ? 
                    ((report.successRequests / report.totalRequests) * 100).toFixed(1) : 0;
                
                const cardHtml = `
                    <div class="col-md-6 col-lg-4 mb-4">
                        <div class="card h-100">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h6 class="mb-0">${escapeHtml(report.testName || '未命名测试')}</h6>
                                <span class="badge bg-info">${escapeHtml(report.format || 'HTML')}</span>
                            </div>
                            <div class="card-body">
                                <div class="row mb-3">
                                    <div class="col-6">
                                        <div class="text-center">
                                            <div class="fs-4 fw-bold text-primary">${AppUtils.formatNumber(report.totalRequests || 0)}</div>
                                            <small class="text-muted">总请求数</small>
                                        </div>
                                    </div>
                                    <div class="col-6">
                                        <div class="text-center">
                                            <div class="fs-4 fw-bold ${successRate >= 95 ? 'text-success' : successRate >= 80 ? 'text-warning' : 'text-danger'}">${successRate}%</div>
                                            <small class="text-muted">成功率</small>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="row mb-3">
                                    <div class="col-6">
                                        <small class="text-muted">平均响应时间</small>
                                        <div>${AppUtils.formatDuration(report.avgResponseTime || 0)}</div>
                                    </div>
                                    <div class="col-6">
                                        <small class="text-muted">QPS</small>
                                        <div>${(report.requestsPerSecond || 0).toFixed(2)}</div>
                                    </div>
                                </div>
                                
                                <div class="row mb-3">
                                    <div class="col-12">
                                        <small class="text-muted">测试时间</small>
                                        <div>${formatDateTime(report.startTime)}</div>
                                    </div>
                                </div>
                                
                                <div class="row mb-3">
                                    <div class="col-12">
                                        <small class="text-muted">持续时长</small>
                                        <div>${AppUtils.formatDuration(report.duration || 0)}</div>
                                    </div>
                                </div>
                            </div>
                            <div class="card-footer">
                                <div class="btn-group w-100" role="group">
                                    <button type="button" class="btn btn-outline-primary btn-sm" onclick="viewReportDetail('${report.sessionId}')">
                                        <i class="fas fa-eye"></i> 查看
                                    </button>
                                    <button type="button" class="btn btn-outline-success btn-sm" onclick="downloadReportFile('${report.sessionId}')">
                                        <i class="fas fa-download"></i> 下载
                                    </button>
                                    <button type="button" class="btn btn-outline-info btn-sm" onclick="shareReport('${report.sessionId}')">
                                        <i class="fas fa-share"></i> 分享
                                    </button>
                                    <button type="button" class="btn btn-outline-danger btn-sm" onclick="deleteReport('${report.sessionId}')">
                                        <i class="fas fa-trash"></i> 删除
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                `;
                
                $('#reports-container').append(cardHtml);
            }

            function formatDateTime(timestamp) {
                if (!timestamp) return 'N/A';
                return new Date(timestamp).toLocaleString('zh-CN');
            }

            function refreshReports() {
                loadReportList();
                AppUtils.showSuccess('报告列表已刷新');
            }

            function applyFilters() {
                const searchTerm = $('#search-input').val().toLowerCase();
                const formatFilter = $('#format-filter').val();
                const timeFilter = $('#time-filter').val();
                
                $('#reports-container .col-md-6').each(function() {
                    const $card = $(this);
                    const testName = $card.find('.card-header h6').text().toLowerCase();
                    const format = $card.find('.badge').text().trim().toLowerCase();
                    
                    let visible = true;
                    
                    // 搜索过滤
                    if (searchTerm && !testName.includes(searchTerm)) {
                        visible = false;
                    }
                    
                    // 格式过滤
                    if (formatFilter && !format.includes(formatFilter.toLowerCase())) {
                        visible = false;
                    }
                    
                    // 时间过滤（简化实现）
                    if (timeFilter) {
                        // 这里可以根据实际需求实现时间过滤逻辑
                    }
                    
                    $card.toggle(visible);
                });
            }

            function viewReportDetail(sessionId) {
                $.get(`/api/reports/${sessionId}`)
                    .done(function(report) {
                        currentReportDetail = report;
                        showReportDetailModal(report);
                    })
                    .fail(function() {
                        AppUtils.showError('加载报告详情失败');
                    });
            }

            function showReportDetailModal(report) {
                const successRate = report.totalRequests > 0 ? 
                    ((report.successRequests / report.totalRequests) * 100).toFixed(2) : 0;
                
                const detailHtml = `
                    <div class="row">
                        <div class="col-md-8">
                            <h6>测试概览</h6>
                            <div class="row mb-4">
                                <div class="col-md-3 text-center">
                                    <div class="card border-0 bg-light">
                                        <div class="card-body py-3">
                                            <div class="fs-3 fw-bold text-primary">${AppUtils.formatNumber(report.totalRequests || 0)}</div>
                                            <small>总请求数</small>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-3 text-center">
                                    <div class="card border-0 bg-light">
                                        <div class="card-body py-3">
                                            <div class="fs-3 fw-bold text-success">${AppUtils.formatNumber(report.successRequests || 0)}</div>
                                            <small>成功请求</small>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-3 text-center">
                                    <div class="card border-0 bg-light">
                                        <div class="card-body py-3">
                                            <div class="fs-3 fw-bold ${successRate >= 95 ? 'text-success' : successRate >= 80 ? 'text-warning' : 'text-danger'}">${successRate}%</div>
                                            <small>成功率</small>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-3 text-center">
                                    <div class="card border-0 bg-light">
                                        <div class="card-body py-3">
                                            <div class="fs-3 fw-bold text-info">${(report.requestsPerSecond || 0).toFixed(0)}</div>
                                            <small>QPS</small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <h6>响应时间统计</h6>
                            <div class="row mb-4">
                                <div class="col-md-4">
                                    <table class="table table-sm">
                                        <tr>
                                            <td>平均响应时间</td>
                                            <td class="text-end">${AppUtils.formatDuration(report.avgResponseTime || 0)}</td>
                                        </tr>
                                        <tr>
                                            <td>最小响应时间</td>
                                            <td class="text-end">${AppUtils.formatDuration(report.minResponseTime || 0)}</td>
                                        </tr>
                                        <tr>
                                            <td>最大响应时间</td>
                                            <td class="text-end">${AppUtils.formatDuration(report.maxResponseTime || 0)}</td>
                                        </tr>
                                    </table>
                                </div>
                                <div class="col-md-8">
                                    <canvas id="responseTimeChart" width="400" height="200"></canvas>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <h6>测试配置</h6>
                            <table class="table table-sm">
                                <tr>
                                    <td>测试名称</td>
                                    <td>${escapeHtml(report.testName || 'N/A')}</td>
                                </tr>
                                <tr>
                                    <td>会话ID</td>
                                    <td><code>${escapeHtml(report.sessionId)}</code></td>
                                </tr>
                                <tr>
                                    <td>并发用户数</td>
                                    <td>${report.concurrentUsers || 'N/A'}</td>
                                </tr>
                                <tr>
                                    <td>测试持续时间</td>
                                    <td>${AppUtils.formatDuration((report.duration || 0) * 1000)}</td>
                                </tr>
                                <tr>
                                    <td>开始时间</td>
                                    <td>${formatDateTime(report.startTime)}</td>
                                </tr>
                                <tr>
                                    <td>结束时间</td>
                                    <td>${formatDateTime(report.endTime)}</td>
                                </tr>
                                <tr>
                                    <td>报告格式</td>
                                    <td><span class="badge bg-info">${report.format || 'HTML'}</span></td>
                                </tr>
                            </table>
                            
                            ${report.scenarios && report.scenarios.length > 0 ? `
                                <h6 class="mt-3">测试场景</h6>
                                <div class="list-group list-group-flush">
                                    ${report.scenarios.map(scenario => `
                                        <div class="list-group-item px-0">
                                            <div class="d-flex justify-content-between align-items-start">
                                                <div class="ms-2 me-auto">
                                                    <div class="fw-bold">${escapeHtml(scenario.name || 'N/A')}</div>
                                                    <small class="text-muted">${escapeHtml(scenario.description || '')}</small>
                                                </div>
                                                <span class="badge bg-primary rounded-pill">${scenario.requests?.length || 0} 请求</span>
                                            </div>
                                        </div>
                                    `).join('')}
                                </div>
                            ` : ''}
                        </div>
                    </div>
                `;
                
                $('#report-detail-content').html(detailHtml);
                new bootstrap.Modal(document.getElementById('reportDetailModal')).show();
                
                // 绘制响应时间图表
                setTimeout(() => {
                    drawResponseTimeChart(report);
                }, 100);
            }

            function drawResponseTimeChart(report) {
                const ctx = document.getElementById('responseTimeChart');
                if (!ctx) return;
                
                new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: report.timePoints || ['开始', '25%', '50%', '75%', '结束'],
                        datasets: [{
                            label: '响应时间 (ms)',
                            data: report.responseTimeData || [
                                report.minResponseTime || 0,
                                (report.minResponseTime || 0) + (report.avgResponseTime || 0) / 2,
                                report.avgResponseTime || 0,
                                (report.avgResponseTime || 0) + (report.maxResponseTime || 0) / 2,
                                report.maxResponseTime || 0
                            ],
                            borderColor: 'rgb(75, 192, 192)',
                            backgroundColor: 'rgba(75, 192, 192, 0.2)',
                            tension: 0.1
                        }]
                    },
                    options: {
                        responsive: true,
                        scales: {
                            y: {
                                beginAtZero: true,
                                title: {
                                    display: true,
                                    text: '响应时间 (ms)'
                                }
                            }
                        }
                    }
                });
            }

            function downloadReport() {
                if (!currentReportDetail) return;
                downloadReportFile(currentReportDetail.sessionId);
            }

            function viewFullReport() {
                if (!currentReportDetail) return;
                window.open(`/reports/${currentReportDetail.sessionId}`, '_blank');
            }

            function downloadReportFile(sessionId) {
                window.location.href = `/api/reports/${sessionId}/download`;
            }

            function shareReport(sessionId) {
                const shareUrl = `${window.location.origin}/reports/${sessionId}`;
                
                if (navigator.clipboard) {
                    navigator.clipboard.writeText(shareUrl).then(() => {
                        AppUtils.showSuccess('分享链接已复制到剪贴板');
                    });
                } else {
                    // 降级处理
                    const textarea = document.createElement('textarea');
                    textarea.value = shareUrl;
                    document.body.appendChild(textarea);
                    textarea.select();
                    document.execCommand('copy');
                    document.body.removeChild(textarea);
                    AppUtils.showSuccess('分享链接已复制到剪贴板');
                }
            }

            function deleteReport(sessionId) {
                if (!confirm('确定要删除这个报告吗？此操作不可恢复。')) return;
                
                $.ajax({
                    url: `/api/reports/${sessionId}`,
                    method: 'DELETE'
                })
                .done(function(response) {
                    if (response.success) {
                        AppUtils.showSuccess('报告已删除');
                        loadReportList();
                    } else {
                        AppUtils.showError(response.message || '删除报告失败');
                    }
                });
            }

            function exportReports() {
                // 批量导出报告
                const selectedReports = []; // 这里可以实现多选功能
                
                if (selectedReports.length === 0) {
                    // 如果没有选择，导出全部
                    window.location.href = '/api/reports/export/all';
                } else {
                    // 导出选中的报告
                    const params = new URLSearchParams();
                    selectedReports.forEach(id => params.append('sessionIds', id));
                    window.location.href = `/api/reports/export?${params.toString()}`;
                }
            }

            function escapeHtml(text) {
                if (!text) return '';
                const div = document.createElement('div');
                div.textContent = text;
                return div.innerHTML;
            }
        </script>
    </th:block>
</html>